package com.terracloud.server.config;

import com.terracloud.server.common.data.id.EntityId;
import com.terracloud.server.dao.model.sql.RoleEntity;
import com.terracloud.server.dao.model.sql.UserRoleEntity;
import com.terracloud.server.dao.sql.role.RoleRepository;
import com.terracloud.server.dao.sql.role.UserRoleRepository;
import com.terracloud.server.dao.sql.user.UserRepository;
import com.terracloud.server.service.entitiy.role.RoleService;
import com.terracloud.server.service.install.InstallScripts;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.transaction.support.TransactionTemplate;

/**
 *
 * @author chenhainan
 * @since 2025/10/20
 */
@Slf4j
@Configuration
@RequiredArgsConstructor
public class InitConfig implements ApplicationListener<ApplicationReadyEvent> {

    private final InstallScripts installScripts;

    private final TransactionTemplate transactionTemplate;

    private final RoleRepository roleRepository;

    private final UserRepository userRepository;

    private final UserRoleRepository userRoleRepository;


    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
//        transactionTemplate.executeWithoutResult(status -> installScripts.loadMenu());
        initRole();
    }

    public void initRole() {
        var sysAdminRole = roleRepository.findByTenantIdAndName(EntityId.NULL_UUID, RoleService.SYS_ADMIN_ROLE);
        if (sysAdminRole == null) {
            sysAdminRole = new RoleEntity();
            sysAdminRole.setTenantId(EntityId.NULL_UUID);
            sysAdminRole.setName(RoleService.SYS_ADMIN_ROLE);
        }
        sysAdminRole.setMenus(RoleService.SYS_ADMIN_MENUS);
        roleRepository.save(sysAdminRole);

        var tenantAdminRole = roleRepository.findByTenantIdAndName(EntityId.NULL_UUID, RoleService.TENANT_ADMIN_ROLE);
        if (tenantAdminRole == null) {
            tenantAdminRole = new RoleEntity();
            tenantAdminRole.setTenantId(EntityId.NULL_UUID);
            tenantAdminRole.setName(RoleService.TENANT_ADMIN_ROLE);
        }
        tenantAdminRole.setMenus(RoleService.TENANT_ADMIN_MENUS);
        roleRepository.save(tenantAdminRole);

        final var sysAdminUser = userRepository.findSysAdminUser();
        final var sysAdminRoleRelation = userRoleRepository.findByUserId(sysAdminUser.getId());
        if (sysAdminRoleRelation == null) {
            UserRoleEntity userRole = new UserRoleEntity();
            userRole.setRoleId(sysAdminRole.getId());
            userRole.setUserId(sysAdminUser.getId());
            userRoleRepository.save(userRole);
        }
    }
}
